package com.g7.figmaapi.web.api.figma.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.zhxu.okhttps.HttpResult;
import cn.zhxu.okhttps.OkHttps;
import com.alibaba.fastjson2.JSONObject;
import com.g7.figmaapi.common.annotation.RedissonLock;
import com.g7.figmaapi.common.constant.CommonConstant;
import com.g7.figmaapi.common.exception.Errors;
import com.g7.figmaapi.common.exception.business.BusinessException;
import com.g7.figmaapi.common.exception.business.ExternalSystemException;
import com.g7.figmaapi.common.result.WebResult;
import com.g7.figmaapi.common.utils.PKCEGeneratorUtils;
import com.g7.figmaapi.common.utils.RedisUtils;
import com.g7.figmaapi.user.dao.UserAuthorizationDao;
import com.g7.figmaapi.user.domain.bo.UserAuthorizationBo;
import com.g7.figmaapi.user.domain.entity.UserAuthorization;
import com.g7.figmaapi.user.mapper.UserAuthorizationMapper;
import com.g7.figmaapi.user.service.UserAuthorizationService;
import com.g7.figmaapi.web.api.enums.WebApiChannelEnum;
import com.g7.figmaapi.web.api.figma.FigmaConstant;
import com.g7.figmaapi.web.api.figma.domain.*;
import com.g7.figmaapi.web.api.figma.domain.dto.*;
import com.g7.figmaapi.web.api.figma.domain.entity.FigmaFileVersion;
import com.g7.figmaapi.web.api.figma.domain.entity.FigmaToken;
import com.g7.figmaapi.web.api.figma.domain.entity.FigmaUser;
import com.g7.figmaapi.web.api.figma.enums.FigmaScopesEnums;
import com.g7.figmaapi.web.api.figma.service.FigmaApiService;
import com.g7.figmaapi.web.api.listener.event.WebApiCallBackEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: taoxiangqian
 * @explain: Figma 相关接口实现
 * @since: 2023/10/25 14:14
 */
@Slf4j
@Service("figmaApiService")
public class FigmaApiServiceImpl implements FigmaApiService {
    @Resource
    private UserAuthorizationDao userAuthorizationDao;
    @Resource
    private UserAuthorizationMapper userAuthorizationMapper;
    @Resource
    private UserAuthorizationService userAuthorizationService;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 服务地址
     */
    @Value("${ip:http://124.71.238.75:8085/}")
    private String ipAddress;

    /**
     * 服务地址
     */
    @Value("${source:G7}")
    private String source;

    /**
     * 基础地址
     */
    private final String baseUrl = "https://www.figma.com";

    private final String apiUrl = "https://api.figma.com";

    /**
     * 用户授权接口
     * <a href="https://www.figma.com/developers/api#oauth2">...</a>
     *
     * @param figmaApiBo figma请求实体
     * @return com.g7.figmaapi.web.api.figma.domain.FigmaApiBo
     * @author taoxiangqian
     * @since 2023/10/26
     **/
    @Override
    @RedissonLock(key = "#figmaApiBo.userId")
    public FigmaApiBo authorization(FigmaApiBo figmaApiBo) {
        // 校验当前用户是否授权
        if (getUserAuthorization(figmaApiBo.getUserId(), false) != null) {
            throw new BusinessException("1", "Authorization failure The current user has been authorized", "授权失败当前用户已授权过无需重复操作");
        }

        // 模拟获取缓存或字典中的figma系统配置
        FigmaBaseConfig figmaBaseConfig = getFigmaConfig();
        if (figmaBaseConfig == null) {
            throw new ExternalSystemException(Errors.SYSTEM_CONFIGURATION_ERROR);
        }


        String randomState = IdUtil.fastSimpleUUID();
        // PCKE模式所需：生成校验码，figma要求长度为43-128个字符，并且只能包含ASCII码中的数字、大小写字母、破折号、下划线、波浪号等字符 todo 暂时不使用PKCE模式
//        String codeVerifier = PKCEGeneratorUtils.generateCodeVerifier();
//        String codeChallenge = PKCEGeneratorUtils.generateCodeChallenge(codeVerifier);
//        log.info("codeVerifier:::{}", codeVerifier);

        // 生成授权地址
        String authorizationUrlStrBuilder = baseUrl +
                "/oauth?client_id=" + figmaBaseConfig.getClientId() +
                "&redirect_uri=" + ipAddress + "/api/web/figmaApi/authorizationCallBack" +
                "&scope=" + FigmaScopesEnums.FILE_CONTENT.getScopes() +
                "&state=" + randomState +
//                "&code_challenge=" + codeChallenge +
//                "&code_challenge_method=S256" +
                "&response_type=code";

        // 信息保存至redis
        Map<String, Object> map = new HashMap<>();
        map.put("userId", figmaApiBo.getUserId().toString());
        map.put("scopes", FigmaScopesEnums.FILE_CONTENT.getScopes());
//        map.put("codeVerifier", codeVerifier);
        boolean isSuccess = RedisUtils.hmset(FigmaConstant.REDIS_KEY_FIGMA_AUTHORIZATION_STATE + randomState, map, 7200L);
        if (!isSuccess) {
            log.error("授权保存code失败:::{}", figmaApiBo.toString());
            throw new BusinessException(Errors.SYSTEM_ERROR);
        }

        FigmaApiBo figmaApiData = new FigmaApiBo();
        figmaApiData.setAuthorizationUrl(authorizationUrlStrBuilder);
        figmaApiData.setUserId(figmaApiBo.getUserId());
        return figmaApiData;
    }

    /**
     * 授权回调接口：
     * 校验state是否与授权接口生成的一致，再通过code调用获取access_token和refresh_token API
     * todo 因PKCE模式参数问题暂时不使用
     * <a href="https://www.figma.com/developers/api#oauth2">...</a>
     *
     * @param figmaCallBackBo 回调实体
     * @author taoxiangqian
     * @since 2023/10/26
     **/
    @Override
    @Transactional
    public WebResult authorizationCallBack(FigmaCallBackBo figmaCallBackBo) {
        //授权回调逻辑
        log.info("进入授权回调处理：{}", figmaCallBackBo.toString());

        FigmaBaseConfig figmaBaseConfig = getFigmaConfig();
        if (figmaBaseConfig == null) {
            log.info("暂未查询到figma配置");
            return WebResult.fail("1", "授权失败", "授权失败", null);
        }

        Map<Object, Object> map = RedisUtils.hmget(FigmaConstant.REDIS_KEY_FIGMA_AUTHORIZATION_STATE + figmaCallBackBo.getState());
        if (StringUtils.isEmpty(String.valueOf(map.get("userId")))) {
            log.info("暂未获取到用户授权信息");
            return WebResult.fail("1", "授权失败", "授权失败", null);
        }

        Long userId = Long.valueOf(String.valueOf(map.get("userId")));
        UserAuthorization currentUserAuthorization = getUserAuthorization(userId, false);
        if (currentUserAuthorization != null) {
            log.error("重复授权{}", currentUserAuthorization.getUserId());
            return WebResult.fail("1", "当前用户已授权", "当前用户已授权", null);
        }

        String authorizationCallBackUrl = ipAddress + "/api/web/figmaApi/authorizationCallBack";
//        String codeVerifier = String.valueOf(map.get("codeVerifier"));

        HttpResult httpResult = OkHttps.sync(baseUrl + "/api/oauth/token")
                .addBodyPara("client_id", figmaBaseConfig.getClientId())
                .addBodyPara("client_secret", figmaBaseConfig.getClientSecret())
                .addBodyPara("redirect_uri", authorizationCallBackUrl)
                .addBodyPara("code", figmaCallBackBo.getCode())
                .addBodyPara("grant_type", "authorization_code")
//                .addBodyPara("code_verifier", codeVerifier)
                .basicAuth(figmaBaseConfig.getClientId(), figmaBaseConfig.getClientSecret())
                .post();

        if (!httpResult.isSuccessful()) {
            log.error("授权请求错误,错误码{}", httpResult.getStatus());
            return WebResult.fail("1", "授权失败", "授权失败",null);
        }


        String scopes = String.valueOf(map.get("scopes"));

        FigmaToken figmaToken = httpResult.getBody().toBean(FigmaToken.class);
        log.info("授权成功响应:{}", figmaToken.toString());

        // 校验用户是否被绑定到其他账号（如果已绑定直接解除）
        userAuthorizationService.execVerifyUserAuthorizationBind(WebApiChannelEnum.FIGMA.getCode(), figmaToken.getUser_id(), userId);

        UserAuthorization userAuthorization = new UserAuthorization();
        userAuthorization.setUserId(userId);
        userAuthorization.setExtId(figmaToken.getUser_id());
        userAuthorization.setAccessToken(figmaToken.getAccess_token());
        userAuthorization.setRefreshToken(figmaToken.getRefresh_token());
        userAuthorization.setExpiresIn(figmaToken.getExpires_in());
        userAuthorization.setScopes(scopes);
        userAuthorization.setChannelType(WebApiChannelEnum.FIGMA.getCode());
        userAuthorization.setChannelId("");
        // 来源申请figma账号的主体（）
        userAuthorization.setAuthorizationSource("G7");
        userAuthorization.setAuthorizationTime(new Date());
        boolean isSuccess = userAuthorizationDao.saveOrUpdateUserAuthorization(userAuthorization);
        if (isSuccess) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    applicationEventPublisher.publishEvent(new WebApiCallBackEvent(this, WebApiChannelEnum.FIGMA.getCode(), WebApiCallBackEvent.EVENT_TYPE_CLEAR_REDIS, FigmaConstant.REDIS_KEY_FIGMA_AUTHORIZATION_STATE + figmaCallBackBo.getState()));
                }
            });
        }
        return WebResult.success(isSuccess);
    }

    /**
     * 刷新用户授权
     * <a href="https://www.figma.com/developers/api#authentication">刷新授权文档</a>
     *
     * @param figmaApiBo 请求实体
     * @return int
     * @author taoxiangqian
     * @since 2023/11/8
     **/
    @Override
    public int refreshAuthorization(FigmaApiBo figmaApiBo) {
        log.info("刷新授权处理：{}", figmaApiBo.toString());

        FigmaBaseConfig figmaBaseConfig = getFigmaConfig();
        if (figmaBaseConfig == null) {
            log.info("暂未查询到figma配置");
            throw new BusinessException(Errors.SYSTEM_CONFIGURATION_ERROR);
        }

        UserAuthorization userAuthorization = getUserAuthorization(figmaApiBo.getUserId(), false);
        if (userAuthorization == null || StringUtils.isEmpty(userAuthorization.getRefreshToken())) {
            throw new BusinessException("1", "", "当前用户暂未授权，无法刷新");
        }

        HttpResult httpResult = OkHttps.sync(baseUrl + "/api/oauth/refresh")
                .addBodyPara("client_id", figmaBaseConfig.getClientId())
                .addBodyPara("client_secret", figmaBaseConfig.getClientSecret())
                .addBodyPara("refresh_token", userAuthorization.getRefreshToken())
                .post();

        if (!httpResult.isSuccessful()) {
            log.error("获取用户信息失败,错误码{}", httpResult.getStatus());
            throw new BusinessException(String.valueOf(httpResult.getStatus()), "", "获取用户信息失败");
        }

        FigmaToken figmaToken = httpResult.getBody().toBean(FigmaToken.class);
        log.info("用户:{},刷新授权返回结果::::{}", figmaApiBo.getUserId(), figmaToken.toString());

        UserAuthorization userAuthorizationParam = new UserAuthorization();
        userAuthorizationParam.setId(userAuthorization.getId());
        userAuthorizationParam.setExpiresIn(figmaToken.getExpires_in());
        userAuthorizationParam.setAccessToken(figmaToken.getAccess_token());
        userAuthorizationParam.setRefreshTime(new Date());
        return userAuthorizationMapper.updateById(userAuthorizationParam);
    }

    @Override
    public int deauthorize(FigmaApiBo figmaApiBo) {
        log.info("解除授权请求参数：{}", figmaApiBo.toString());
        UserAuthorization userAuthorization = getUserAuthorization(figmaApiBo.getUserId(), true);
        if (userAuthorization == null || StringUtils.isEmpty(userAuthorization.getRefreshToken())) {
            throw new BusinessException("1", "", "当前用户暂未授权，无法解除");
        }
        UserAuthorization userAuthorizationParam = new UserAuthorization();
        userAuthorizationParam.setId(userAuthorization.getId());
        userAuthorizationParam.setIsEnabled(CommonConstant.IS_NOT_ENABLED);
        return userAuthorizationMapper.updateById(userAuthorizationParam);
    }

    @Override
    public FigmaUser selUsers(FigmaApiBo figmaApiBo) {
        log.info("查询用户信息请求参数：{}", figmaApiBo.toString());
        UserAuthorization userAuthorization = getUserAuthorization(figmaApiBo.getUserId(), true);
        if (userAuthorization == null || StringUtils.isEmpty(userAuthorization.getRefreshToken())) {
            throw new BusinessException("1", "", "当前用户暂未授权，无法获取文件版本");
        }

        FigmaBaseConfig figmaBaseConfig = getFigmaConfig();
        if (figmaBaseConfig == null) {
            log.info("暂未查询到figma配置");
            throw new BusinessException(Errors.SYSTEM_CONFIGURATION_ERROR);
        }

        HttpResult httpResult = OkHttps.sync(apiUrl + "/v1/me")
                .bearerAuth(userAuthorization.getAccessToken())
                .get();


        if (!httpResult.isSuccessful()) {
            log.error("获取用户信息失败,错误码{}", httpResult.getStatus());
            throw new BusinessException(String.valueOf(httpResult.getStatus()), "", "获取用户信息失败");
        }
        return httpResult.getBody().toBean(FigmaUser.class);
    }

    @Override
    public FigmaFileVersion selFileVersion(FigmaFileVersionBo figmaFileVersionBo) {
        log.info("查询文件版本请求参数：{}", figmaFileVersionBo.toString());
        String fileUrlKey = getFigmaFileKey(figmaFileVersionBo.getFileUrl());
        UserAuthorization userAuthorization = getUserAuthorization(figmaFileVersionBo.getUserId(), true);
        if (userAuthorization == null || StringUtils.isEmpty(userAuthorization.getRefreshToken())) {
            throw new BusinessException("1", "", "当前用户暂未授权，无法获取文件版本");
        }

        FigmaBaseConfig figmaBaseConfig = getFigmaConfig();
        if (figmaBaseConfig == null) {
            log.info("暂未查询到figma配置");
            throw new BusinessException(Errors.SYSTEM_CONFIGURATION_ERROR);
        }

        HttpResult httpResult = OkHttps.sync(apiUrl + "/v1/files/{fileUrlKey}/versions")
                .addPathPara("fileUrlKey", fileUrlKey)
                .bearerAuth(userAuthorization.getAccessToken())
                .bodyType("urlencoded")
                .get();

        if (!httpResult.isSuccessful()) {
            log.error("授权请求错误,错误码{}", httpResult.getStatus());
            throw new BusinessException(String.valueOf(httpResult.getStatus()), "", "外部系统响应失败");
        }
        return httpResult.getBody().toBean(FigmaFileVersion.class);
    }

    @Override
    public String selFile(FigmaFileBo figmaFileBo) {
        log.info("查询文件信息请求参数：{}", figmaFileBo.toString());
        String fileUrlKey = getFigmaFileKey(figmaFileBo.getFileUrl());
        UserAuthorization userAuthorization = getUserAuthorization(figmaFileBo.getUserId(), true);
        if (userAuthorization == null || StringUtils.isEmpty(userAuthorization.getRefreshToken())) {
            throw new BusinessException("1", "", "当前用户暂未授权，无法获取文件版本");
        }

        FigmaBaseConfig figmaBaseConfig = getFigmaConfig();
        if (figmaBaseConfig == null) {
            log.info("暂未查询到figma配置");
            throw new BusinessException(Errors.SYSTEM_CONFIGURATION_ERROR);
        }

        // 拼装参数
        Map<String, Object> paramMap = parametricAssembly(figmaFileBo);
        log.info("参数{}", JSONObject.toJSONString(paramMap));
        HttpResult httpResult = OkHttps.sync(apiUrl + "/v1/files/{fileUrlKey}")
                .addPathPara("fileUrlKey", fileUrlKey)
                .addUrlPara(paramMap)
                .bearerAuth(userAuthorization.getAccessToken())
                .get();

        if (!httpResult.isSuccessful()) {
            log.error("授权请求错误,错误码{}", httpResult.getStatus());
            throw new BusinessException(String.valueOf(httpResult.getStatus()), "", "获取文件信息失败，请确认文件存在并且链接权限为所有人可访问");
        }
        return httpResult.getBody().toString();
    }

    /**
     * 参数拼装
     *
     * @param figmaObject 请求实体
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author taoxiangqian
     * @since 2023/11/12 20:14:47
     **/
    private <T> Map<String, Object> parametricAssembly(T figmaObject) {
        Map<String, Object> parameters = new HashMap<>();
        if (figmaObject == null) {
            return parameters;
        }

        Class<?> clazz = figmaObject.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(figmaObject);
                if (value != null && !field.getName().equals("userId") && !field.getName().equals("fileUrl")) {
                    parameters.put(field.getName(), value);
                }
            } catch (IllegalAccessException e) {
                log.error("参数拼接错误{}", e.getMessage());
            }
        }

        return parameters;
    }


    @Override
    public String selFileNodes(FigmaFileNodesBo figmaFileNodesBo) {
        log.info("查询文件节点信息请求参数：{}", figmaFileNodesBo.toString());
        String fileUrlKey = getFigmaFileKey(figmaFileNodesBo.getFileUrl());
        UserAuthorization userAuthorization = getUserAuthorization(figmaFileNodesBo.getUserId(), true);
        if (userAuthorization == null || StringUtils.isEmpty(userAuthorization.getRefreshToken())) {
            throw new BusinessException("1", "", "当前用户暂未授权，无法获取文件版本");
        }

        FigmaBaseConfig figmaBaseConfig = getFigmaConfig();
        if (figmaBaseConfig == null) {
            log.info("暂未查询到figma配置");
            throw new BusinessException(Errors.SYSTEM_CONFIGURATION_ERROR);
        }

        // 拼装参数
        Map<String, Object> paramMap = parametricAssembly(figmaFileNodesBo);
        HttpResult httpResult = OkHttps.sync(apiUrl + "/v1/files/{fileUrlKey}/nodes")
                .addPathPara("fileUrlKey", fileUrlKey)
                .addUrlPara(paramMap)
                .bearerAuth(userAuthorization.getAccessToken())
                .bodyType("urlencoded")
                .get();
        if (!httpResult.isSuccessful()) {
            log.error("授权请求错误,错误码{}", httpResult.getStatus());
            throw new BusinessException(String.valueOf(httpResult.getStatus()), "", "获取文件节点信息失败，请确认当前链接权限为所有人可访问");
        }
        return httpResult.getBody().toString();
    }

    @Override
    public String selImage(FigmaImageBo figmaImageBo) {
        log.info("查询文件图像信息请求参数：{}", figmaImageBo.toString());
        String fileUrlKey = getFigmaFileKey(figmaImageBo.getFileUrl());
        UserAuthorization userAuthorization = getUserAuthorization(figmaImageBo.getUserId(), true);
        if (userAuthorization == null || StringUtils.isEmpty(userAuthorization.getRefreshToken())) {
            throw new BusinessException("1", "", "当前用户暂未授权，无法获取文件版本");
        }

        FigmaBaseConfig figmaBaseConfig = getFigmaConfig();
        if (figmaBaseConfig == null) {
            log.info("暂未查询到figma配置");
            throw new BusinessException(Errors.SYSTEM_CONFIGURATION_ERROR);
        }

        // 拼装参数
        Map<String, Object> paramMap = parametricAssembly(figmaImageBo);
        HttpResult httpResult = OkHttps.sync(apiUrl + "/v1/images/{fileUrlKey}")
                .addPathPara("fileUrlKey", fileUrlKey)
                .addUrlPara(paramMap)
                .bearerAuth(userAuthorization.getAccessToken())
                .bodyType("urlencoded")
                .get();
        if (!httpResult.isSuccessful()) {
            log.error("授权请求错误,错误码{}", httpResult.getStatus());
            throw new BusinessException(String.valueOf(httpResult.getStatus()), "", "获取图片信息失败，请确认当前链接权限为所有人可访问");
        }
        return httpResult.getBody().toString();
    }

    @Override
    public String selImageFills(FigmaImageFillsBo figmaImageFillsBo) {
        log.info("查询文件图像填充信息请求参数：{}", figmaImageFillsBo.toString());
        String fileUrlKey = getFigmaFileKey(figmaImageFillsBo.getFileUrl());
        UserAuthorization userAuthorization = getUserAuthorization(figmaImageFillsBo.getUserId(), true);
        if (userAuthorization == null || StringUtils.isEmpty(userAuthorization.getRefreshToken())) {
            throw new BusinessException("1", "", "当前用户暂未授权，无法获取文件版本");
        }

        FigmaBaseConfig figmaBaseConfig = getFigmaConfig();
        if (figmaBaseConfig == null) {
            log.info("暂未查询到figma配置");
            throw new BusinessException(Errors.SYSTEM_CONFIGURATION_ERROR);
        }

        HttpResult httpResult = OkHttps.sync(apiUrl + "/v1/files/{fileUrlKey}/images")
                .addPathPara("fileUrlKey", fileUrlKey)
                .bearerAuth(userAuthorization.getAccessToken())
                .bodyType("urlencoded")
                .get();
        if (!httpResult.isSuccessful()) {
            log.error("授权请求错误,错误码{}", httpResult.getStatus());
            throw new BusinessException(String.valueOf(httpResult.getStatus()), "", "获取文件图片失败，请确认当前链接权限为所有人可访问");
        }
        return httpResult.getBody().toString();
    }

    // FIGMA 文件地址规则
    private static final String FIGMA_URL_PATTERN = "^https://www.figma.com/file/([0-9a-zA-Z]+)/?.*";
    private static final Pattern pattern = Pattern.compile(FIGMA_URL_PATTERN);

    /**
     * 获取路径中的key，并校验是否为合法路径
     *
     * @param fileUrl 文件路径
     * @return java.lang.String
     * @author taoxiangqian
     * @since 2023/11/12 17:02:10
     **/
    private static String getFigmaFileKey(String fileUrl) {
        Pattern.compile(FIGMA_URL_PATTERN);
        Matcher matcher = pattern.matcher(fileUrl);
        if (!matcher.matches()) {
            throw new BusinessException("1", "当前文件地址不正确", "当前文件地址不正确");
        }
        return matcher.group(1);
    }

    /**
     * 获取用户授权信息
     *
     * @param userId                    用户ID
     * @param verifyAuthorizationExpire 是否校验授权过期
     * @return com.g7.figmaapi.user.domain.entity.UserAuthorization 用户授权信息
     * @author taoxiangqian
     * @since 2023/11/8
     **/
    private UserAuthorization getUserAuthorization(Long userId, Boolean verifyAuthorizationExpire) {
        UserAuthorizationBo userAuthorizationParam = new UserAuthorizationBo();
        userAuthorizationParam.setUserId(userId);
        userAuthorizationParam.setChannelType(WebApiChannelEnum.FIGMA.getCode());
        userAuthorizationParam.setAuthorizationSource(source);
        UserAuthorization userAuthorization = userAuthorizationDao.getUserAuthorizationOneByParam(userAuthorizationParam);

        if (userAuthorization == null) {
            return userAuthorization;
        }

        Date currentTime = new Date();
        Date expiryTime = new Date(currentTime.getTime() - userAuthorization.getExpiresIn() * 1000);
        // 判断是否校验授权时间
        if (verifyAuthorizationExpire && currentTime.getTime() - expiryTime.getTime() > userAuthorization.getRefreshTime().getTime()) {
            throw new BusinessException("1", "当前账户授权已过期", "当前账户授权已过期");
        }

        return userAuthorization;
    }

    /**
     * 模拟获取figma配置
     *
     * @return com.g7.figmaapi.web.api.figma.domain.FigmaBaseConfig
     * @author taoxiangqian
     * @since 2023/11/8
     **/
    private FigmaBaseConfig getFigmaConfig() {
        FigmaBaseConfig figmaBaseConfig = new FigmaBaseConfig();
        figmaBaseConfig.setClientId("7iJdAGju7IgUrQcZS1kdx7");
        figmaBaseConfig.setClientSecret("j6gl42vnaNL8dJuDqPHkAV1wqK05Kf");
        return figmaBaseConfig;
    }
}
